/*
 * Copyright (c) 2020-2021. the original authors and DEPSEA.ORG
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.depsea.log.aop.advice;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.depsea.log.point.MethodContext;
import org.depsea.log.point.MethodPoint;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.ThrowsAdvice;
import org.springframework.lang.NonNull;

import java.lang.reflect.Method;

/**
 * @author jaune
 * @since 1.0.0
 */
@Slf4j
public class MethodAdvice extends AbstractMethodAdvice implements AfterReturningAdvice, ThrowsAdvice, MethodBeforeAdvice {

    private final ThreadLocal<MethodPoint> local = new ThreadLocal<>();

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        log.info("Execute method : {}#{}", method.getDeclaringClass().getName(), method.getName());
        MethodPoint methodPoint = this.local.get();
        if (methodPoint == null) {
            methodPoint = new MethodPoint();
            local.set(methodPoint);

            MethodContext methodContext = this.createMethodContext(method, args);
            methodPoint.setRoot(methodContext);
        } else {
            MethodContext methodContext = this.createMethodContext(method, args);
            methodPoint.addChildren(methodContext);
        }
    }

    @Override
    public void afterReturning(Object returnValue, @NonNull Method method, @NonNull Object[] args, Object target) throws Throwable {
        MethodPoint methodPoint = this.local.get();
        long end = System.currentTimeMillis();
        methodPoint.getCurrent().setReturnValue(this.objectMapper.writeValueAsString(returnValue));
        methodPoint.getCurrent().setTimeConsuming(end - methodPoint.getCurrent().getStart());
        methodPoint.up();
    }

    public void afterThrowing(Method method, Object[] args, Object target, Exception ex) {
        MethodPoint methodPoint = this.local.get();
        long end = System.currentTimeMillis();
        methodPoint.getCurrent().setTimeConsuming(end - methodPoint.getCurrent().getStart());
        methodPoint.up();
    }

    private MethodContext createMethodContext(Method method, Object[] args) throws JsonProcessingException {
        MethodContext methodContext = new MethodContext();
        methodContext.setMethodName(method.getName());
        methodContext.setClazz(method.getDeclaringClass().getName());
        methodContext.setStart(System.currentTimeMillis());

        methodContext.setParametersMap(this.objectMapper.writeValueAsString(
                this.getMethodParameterMap(method, args)));
        return methodContext;
    }

}
